package com.skyline.imagine.web;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

/**
 * 1、SWF图片上传必须为servlet，因为使用springMVC会返回406
 * 2、仅支持UTF-8编码，因为JsonEncoding仅支持UTF8，UTF16_BE，UTF16_LE，UTF32_BE，UTF32_LE
 * 
 * @author wuqh
 */
public class SwfUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 8143434173541206819L;
	private static final Log logger = LogFactory.getLog(SwfUploadServlet.class);
	private static final JsonEncoding CHARSET = JsonEncoding.UTF8;

	private transient CommonsMultipartResolver multipartResolver;
	private transient SwfUploadAction swfUploadAction;
	private transient ObjectMapper objectMapper = new ObjectMapper();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SwfUploadServlet() {
		super();
	}

	@Override
	public void init() throws ServletException {
		super.init();
		initUploadConfig();
	}

	private void initUploadConfig() {
		getInitParameter("resize");

		WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		multipartResolver = ctx.getBean(CommonsMultipartResolver.class);
		swfUploadAction = ctx.getBean(SwfUploadAction.class);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		try {
			if (multipartResolver.isMultipart(request)) {
				request = multipartResolver.resolveMultipart(request);
				Map<String, Object> result = swfUploadAction.fileUpload((MultipartHttpServletRequest) request);
				writeJson(response, result);
				multipartResolver.cleanupMultipart((MultipartHttpServletRequest) request);
			} else {
				logger.debug("请求非multipart类型，不包含文件！");
				writeJson(response, swfUploadAction.getNoFileExistErrMsg());
			}
		} catch (Exception e) {
			logger.error("上传文件失败！", e);
			writeJson(response, swfUploadAction.getNoFileExistErrMsg());
		}

	}

	private void writeJson(HttpServletResponse response, Map<String, Object> responseBody) throws IOException {
		JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(response.getOutputStream(),
				CHARSET);
		try {
			objectMapper.writeValue(jsonGenerator, responseBody);
		} catch (JsonProcessingException ex) {
			throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
		}
	}

}
